<?php

class Util
{
	private static $_msgs = null;

	public static function generateToken()
	{
		return md5(uniqid(mt_rand()));
	}
	public static function encodePassword($password)
	{
		return md5($password.PASSWORD_SALT);
	}
	
	/**
	 * Returns the JSON representation of a value
	 * 
	 * @param  $value The value being encoded
	 * @return the JSON representation of a value
	 */
	public static function getJsonData($value)
	{
		$json = json_encode($value);
		//
		return $json;
		// 
		return preg_replace("#\\\u([0-9a-f]+)#ie", "iconv('UCS-2', 'UTF-8', pack('H4', '\\1'))", $json);
	}
	/**
	 * Get the message by message code.
	 * 
	 * @param  $errorCode The Message Code
	 * @return String the message
	 */
	public static function getMessage($errorCode, $param = array())
	{
		if (null == self::$_msgs)
		{
			// Get the app config
	        $dir = Q::ini("app_config");
            self::$_msgs = parse_ini_file($dir['APP_DIR']."/config/message.ini");
		}
		if (array_key_exists($errorCode, self::$_msgs))
		{
			$msg = self::$_msgs[$errorCode];
			if (is_string($param))
			{
				$msg = str_replace('{0}', $param, $msg);
			}
			else
			{
				foreach($param as $i => $value)
				{
					$msg = str_replace('{'.$i.'}', $value, $msg);
				}
			}
			return $msg;
		}
		else
		{
		    return "";
		}
	}
	
	/**
     * Format the datetime
     * 
     * @param  String  $info 
     * @return String|Array the user info
     */
	public static function df($datetime, $formatStr = 'Y.m.d')
	{
		if (empty($datetime)) 
		{
			return "";
		}
		else
		{
		  return date($formatStr, $datetime);
		}
	}

    /**
     * Get the client ip address
     * 
     * @param  void
     * @return String    the client ip address
     */
	public static function getClientIp()
	{
		$ip = "";
		if(isset($_SERVER['HTTP_CLIENT_IP'])) {
		    $ip = $_SERVER['HTTP_CLIENT_IP'];
		}else if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
		    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		}else{
		    $ip = $_SERVER['REMOTE_ADDR'];
		}
		return $ip;
	}
    
	public static function generateEmail($template, $param)
	{
		$email = array();
		$subject = $template['subject'];
		$content = $template['content'];
		foreach ($param as $k => $v)
		{
			$subject = str_replace('{$'.$k.'$}', $v, $subject);
			$content = str_replace('{$'.$k.'$}', $v, $content);
		}
		$email['subject'] = $subject;
		$email['content'] = $content;
		$email['sender'] = $template['sender'];
		return $email;
	}
	public static function getCampaignPixelPosition($pos)
	{
		switch ($pos)
		{
			case 1:
				return "After Landing";
			case 2:
				return "After Basic Registration";
			case 3:
				return "After Full Registration";
			default:
				return "Unknown";

		}
	}
	public static function getCreativeType($type)
	{
		switch ($type)
		{
			case 1:
				return 'Image';
			case 2:
				return 'Flash';
			case 3:
				return 'Email';
			default:
				return 'Unknown';
		}
	}
	public static function getCreativeSize($size)
	{
		switch ($size)
		{
			case 1:
				return 'Medium Rectangle (300 x 250)';
			case 2:
				return 'Rectangle (180 x 150)';
			case 3:
				return 'Leaderboard (728 x 90)';
			case 4:
				return 'Wide Skyscraper (160 x 600)';
			case 5:
				return 'Half Page Ad (300 x 600)';
			case 6:
				return 'Button 2 (120 x 60)';
			case 7:
				return 'Micro Bar (88 x 31)';
			default:
				return 'Unknown';
		}
	}
	public static function getSiteGame($game)
	{
		switch ($game)
		{
			case 1:
				return 'Slot';
			case 2:
				return 'Wheel';
			case 3:
				return 'Poker';
			default:
				return 'Unknown';
			
		}
	}
	
	public static function getOfferStatus($status){
		switch ($status){
			case 0:
				return 'Pending';
			case 1:
				return 'Active';
			case 2:
				return 'Pause';
			case 3:
				return 'Delete';
			default:
				return 'Unknown';
		}
	}
	
	public static function getOfferConvPos($convPos){
		switch ($convPos){
			case 0:
				return 'Landing';
			case 1:
				return 'Short Register';
			case 2:
				return 'Long Register';
			default:
				return 'Unknown';
		}
	}
	
	public static function getOfferAvailability($availability){
		switch ($availability){
			case 0:
				return 'Public';
			case 1:
				return 'Private';
			default:
				return 'Unknown';
		}
	}
	
	public static function getFulfillmentStatus($status){
		switch ($status){
			case 0:
				return 'Pending';
			case 1:
				return 'Completed';
			case 2:
				return 'Cancelled';
			case 3:
				return 'Check Returned';
			default:
				return 'Unknown';
		}
	}
	
	public static function getAllFulfillmentStatus(){
		return array(
			0 => 'Pending',
			1 => 'Completed',
			2 => 'Cancelled',
			3 => 'Check Returned',
			'Unknown'
		);
	}
	
	public static function getPixelType($type){
		switch ($type){
			case 0:
				return 'Image';
			case 1:
				return 'Iframe';
			case 2:
				return 'Javascript';
			default:
				return 'Unknown';
		}
	}
	
	/**
	 * 
	 * Build a dropdownlist
	 * @param array $attrs
	 * @param array $options
	 * @param mixed $selectedValue
	 * @param mixed $defaultOption  specify a defautl option for the dropdownlist (eg: array('v'=>1, 'l'=>'One') <option value="1">One</option>)
	 */
	public static function buildDropDownList($attrs, $options, $selectedValue=false, $defaultOption=false)
	{
		$out = '<select';
		foreach ($attrs as $k=>$v){
			$out .= " $k=" . '"' . $v . '"';
		}
		$out .= '>';
		if($defaultOption){
			$out .= '<option value="' . $defaultOption['v'] . '">' . $defaultOption['l'] . '</option>';
		}
		if(!empty($options)){
			foreach ($options as $v=>$l){
				if(!$selectedValue){
					$out .= '<option value="' . $v . '">' . $l . '</option>';
				}else{
					if($v == $selectedValue){
						$out .= '<option value="' . $v . '" selected="selected">' . $l . '</option>';
					}else{
						$out .= '<option value="' . $v . '">' . $l . '</option>';
					}
				}
			}
		}
		$out .= '</select>';
		return $out; 
	}
	
	/**
	 * 
	 * Generate a data provider for dropdownlist
	 * @param array $source   usually it's a result set return by sql query
	 * @param string $valueField  
	 * @param string $labelField
	 */
	public static function listData($source, $valueField, $labelField)
	{
		if($source == null)
			return false;
		$dataProvider = array();
		foreach ($source as $data){
			$dataProvider[$data[$valueField]] = $data[$labelField];
		}
		return $dataProvider;
	}
	
	public static function listDataMonetizations($monetizations)
	{
		if ($monetizations == null)
		{
			return false;
		}
		$ds = array();
		foreach ($monetizations as $monetization)
		{
			$ds[$monetization['id']] = $monetization['id'] . ' - ' . $monetization['name'] . ' - ' . $monetization['note'];
		}
		return $ds;
	}
	
	public static function listDataOffers($offers){
		$ds = array();
		foreach ($offers as $offer){
			$ds[$offer['id']] = $offer['name'] . ', ' . $offer['type'] . ', $' . $offer['price'];
		}
		return $ds;
	}
	
	public static function getTemplates($path){
		clearstatcache();
		$templates = array();
		if ($handle = opendir($path)) {
			chdir($path);
	    	while (false !== ($file = readdir($handle))) {
		        if ($file != "." && $file != ".." && is_dir($file) && $file != '.svn') {
		            $templates[$file] = $file;
		        }
		    }
		    closedir($handle);
		}
		return $templates;
	}
	
	//getting report duration
	public static function getReportDuration($duration, $customrangedate=array()){
		$durations = array();
		switch ($duration){
			case '0':
				$durations[] = self::formateDate(TimeUtil::startOfToday());
				$durations[] = self::formateDate(TimeUtil::endOfToday());
				break;
			case '1':
				$durations[] = self::formateDate(TimeUtil::startOfYesterday());
				$durations[] = self::formateDate(TimeUtil::startOfToday());
				break;
			case '2':
				$durations[] = self::formateDate(TimeUtil::startOfLast7Days());
				$durations[] = self::formateDate(TimeUtil::startOfToday());
				break;
			case '3':
				$durations[] = self::formateDate(TimeUtil::startOfMonth());
				$durations[] = self::formateDate(TimeUtil::startOfToday());
				break;
			case '4':
				$durations[] = $customrangedate['start'];
				$durations[] = $customrangedate['end'];
				break;
			default:
				$start = self::formateDate(time());
				$durations[] = $start;
				$durations[] = $start;
				break;
		}
		return $durations;
	}
	
	private static function formateDate($ts){
		return date('m/d/Y', $ts);
	}
	
	public static function weekBorder($datestr, $weekborder='end'){
		$ts = strtotime($datestr);
		$format = 'm/d/Y';

		$dayofweek = explode('/', $datestr);
		$ts = ($weekborder=='end') ? (strtotime($datestr) + 60*60*24*6) : (strtotime($dayofweek[1]) - 60*60*24*($dayofweek[0]));
	
		return date($format, $ts);
	}
	
	public static function divide($left_operand, $right_operand, $decimals, $per = false) {
		// except for numbers like 0.00
		if (empty($right_operand) || intval($right_operand) == 0) {
			return '---';
		}
		if ($per)
		{
			$result = bcdiv($left_operand * 100, $right_operand, $decimals);
			return $result . '%';
		}
		else
		{
			$result = bcdiv($left_operand, $right_operand, $decimals);
			return $result;
		}
	}
	
	/*
	 * args
	 */
	public static function getProportionAB()
	{
		$args = func_get_args();
		$decimals = $args[0];
		$a = $args[1];
		unset($args[0]);
		$total = 0;
		foreach($args as $k=>$v){
			$total += $v;
		}
		
		if($total == 0){
			return 0 . '%';
		}else{
			return bcdiv($a * 100, $total, $decimals) . '%';
		}
	}
	
	
	/**		
	 * --------------exist for test----------------
	 * if can't add this  email to db, return false
	 */
	public static function addNewEmail($tag, $site_template, $args){
		$template_model = new Template();
		
		if($template = $template_model->getTemplate($tag, $site_template)){
			$content = self::translateTemplate($template,  $args);
			$subject = self::getEmailSubject($tag, $site_template, $args);
			$email = new Email();
			$priority = empty($args['priority'])?0:$args['priority'];
			if ($tag == 'share') {
				if($email->addShareSentEmail($site_template, 'no-reply@' . strtolower($args['domain']), $subject, $args['email'], $content, $args['reference'], $priority)){
					//return true;
				}
			}else if($email->addSentEmail($site_template, 'no-reply@' . strtolower($args['domain']), $subject, $args['email'], $content, $priority, $tag)){
				//return true;
			}
		}
		return false;		
	}
	
	
	public static function addNewEmailFlow($templateId, $site_id, $args = array()){
		$template_model = new Template();
		$emailModel = new Email();
		$template = $emailModel->getEmailTemplateInfoById($templateId);
		if($template){
			$tag = $template['template_name'];
			$content = $template['content'];
			$subject = $template['template_subject'];
			$priority = empty($args['priority'])? 0 : $args['priority'];
			
			$siteModel = new Site();
			if($site_id == '0'){
				$sites = $siteModel->getAllSites();
				foreach($sites as $k => $site){
					$templateHeadFoot = $template_model->getHeaderFootTemplate($site['template']);
					$emailContent = $templateHeadFoot['header'] . $content . $templateHeadFoot['foot'];
					if(!$emailModel->addSentEmail($site['domain'], 'no-reply@' . strtolower($site['domain']), $subject, $args['email'], $emailContent, $priority, $tag)){
						return false;
					}
				}
				return true;
			}else{
				$site = $siteModel->getSiteById($site_id);
				$templateHeadFoot = $template_model->getHeaderFootTemplate($site['template']);
				$emailContent = $templateHeadFoot['header'] . $content . $templateHeadFoot['foot'];
				return $emailModel->addSentEmail($site['domain'], 'no-reply@' . strtolower($site['domain']), $subject, $args['email'], $emailContent, $priority, $tag);				
			}
		}		
	}
	
	public static function getSiteTpls($site){
		$template_root = Q::ini('appini/template_root');
		$dir = $template_root.'/'.$site.'/email';
		$tpls = Array();
		if ($handle = opendir($dir)) {
		    while (false !== ($file = readdir($handle))) {
		    	list($filename, $ext) = split('[.]', $file);
		        if($ext == 'html'){
		        	$tpls[] = $filename;
		        }
		    }
		
		    closedir($handle);
		}
		
		return $tpls;
	}
	
	public static function getVariance(array $rawdata, $field) {
		$totalNums = count($rawdata);
		$total = 0;
		foreach ($rawdata as $data) {
			$total += $data[$field];
		}
		$avarage = $total / $totalNums;
		
		$varianceTotal = 0;
		foreach ($rawdata as $data) {
			$varianceTotal += pow(($data[$field] - $avarage), 2);
		}
		
		return sprintf("%.2f", ($varianceTotal / $totalNums));
	}
	
	public static function translate($content, $args){
		foreach ($args as $k => $v){
			$content = str_replace('[[' . $k . ']]', $v, $content);
		}
		return $content;
	}
	
	
	private static function translateTemplate($content, $args){
		foreach ($args as $k => $v){
			$content = str_replace('[[' . $k . ']]', $v, $content);
		}
		return $content;
	}
	
	public static function getEmailSubject($tag, $site_template, $args, $config_dbOrFile = 'file', $site_id = 1){
		if($config_dbOrFile == 'file'){
			$config = Q::ini('appini/template_root').'/'.$site_template . '/email/email.ini';
			$subjects = parse_ini_file($config);
			$subject = isset($subjects[$tag]) ? $subjects[$tag] :false;
		}else if($config_dbOrFile == 'db'){
			switch($tag){
				case 'offersofweek':
					$emailOffersModel = new EmailOffers();
					$subject = $emailOffersModel->getOfferEmailSubject($site_id);
					break;
				default:
					break;
			}
		}
		if($subject){
			return self::translateTemplate($subject, $args);
		}
		return false;
	}
	
	
	public static function getStartAndEndDate($week, $year) {
		$time = strtotime("1 January $year", time());
		$day = date('w', $time);
		$time += ((7*$week)-$day)*24*3600;
		$return['start'] = date('m/d/Y', $time);
		$time += 6*24*3600;
		$return['end'] = date('m/d/Y', $time);
		
		return $return;
	}
	
	public static function getRandonPassword($length = 6){
		$password = array();
		$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
	    $count = strlen($chars);
	
	    for ($i = 0, $result = ''; $i < $length; $i++) {
	        $index = rand(0, $count - 1);
	        $result .= substr($chars, $index, 1);
	    }
	    
	 	$password[] = $result;
	 	$password[] = self::encodePassword($result);
	    return $password;
	}
}
